package org.example;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

public class JdbcTransaction implements Transaction{

    private DataSource dataSource;

    private Connection connection;

    private boolean autoCommit;


    public JdbcTransaction(Connection connection) {
        this.connection = connection;
        this.autoCommit = true;
    }

    public JdbcTransaction(DataSource dataSource, boolean autoCommit) {
        this.dataSource = dataSource;
        this.autoCommit = autoCommit;
    }

    @Override
    public Connection getConnection() throws SQLException {
        Connection result;
        if(connection != null) {
            result = connection;
        } else {
            result = dataSource.getConnection();
        }
        result.setAutoCommit(autoCommit);
        return result;
    }
}
